<template>
  <div class="donation-total">
    <!-- 顶部暖色横幅 -->
    <section class="hero">
      <div class="hero-left">
        <h1>爱心总览 · 受助人照片墙</h1>
        <p>每一份善意，都会被看见。感谢你的关怀与支持。</p>
        <div class="hero-stats">
          <div class="stat">
            <div class="stat-num">¥ {{ grandTotal.toLocaleString() }}</div>
            <div class="stat-label">累计捐赠金额</div>
          </div>
          <div class="stat">
            <div class="stat-num">{{ totalRecipients }}</div>
            <div class="stat-label">受助人数量</div>
          </div>
          <div class="stat">
            <div class="stat-num">{{ totalDonations }}</div>
            <div class="stat-label">捐赠笔数</div>
          </div>
        </div>
      </div>
      <div class="hero-right">
        <svg viewBox="0 0 200 200" class="hero-illustration" aria-hidden="true">
          <defs>
            <linearGradient id="dt-g1" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0%" stop-color="#FF8A80"/>
              <stop offset="100%" stop-color="#FF5252"/>
            </linearGradient>
            <linearGradient id="dt-g2" x1="1" x2="0" y1="0" y2="1">
              <stop offset="0%" stop-color="#FFD180"/>
              <stop offset="100%" stop-color="#FF9E80"/>
            </linearGradient>
          </defs>
          <path d="M100 170 C 30 120, 10 90, 30 60 C 50 30, 85 40, 100 60 C 115 40, 150 30, 170 60 C 190 90, 170 120, 100 170 Z"
                fill="url(#dt-g1)"/>
          <circle cx="150" cy="50" r="10" fill="url(#dt-g2)" opacity="0.9"/>
          <circle cx="60" cy="40" r="6" fill="white" opacity="0.65"/>
        </svg>
      </div>
    </section>

    <!-- 工具条 -->
    <el-card class="toolbar-card">
      <el-form :inline="true" :model="filter">
        <el-form-item label="搜索受助人">
          <el-input v-model="filter.keyword" placeholder="如：王阿姨 / 爱心基金" clearable @keyup.enter="load"/>
        </el-form-item>
        <el-form-item label="显示 Top N">
          <el-input-number v-model="filter.topN" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="filter.sortBy" style="width: 160px">
            <el-option label="按金额从高到低" value="amountDesc" />
            <el-option label="按金额从低到高" value="amountAsc" />
            <el-option label="按最近时间" value="latest" />
            <el-option label="按名称" value="name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="load">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 照片卡片墙 -->
    <section class="grid">
      <el-empty v-if="!loading && cards.length === 0" description="暂无捐赠汇总数据" />
      <transition-group name="fade" tag="div" class="cards">
        <div v-for="it in visibleCards" :key="it.recipient" class="card">
          <div class="photo">
            <img v-if="it.photo_url" :src="it.photo_url" :alt="it.recipient" @error="it.photo_url=''" />
            <div v-else class="avatar" :style="avatarStyle(it.recipient)">
              {{ initials(it.recipient) }}
            </div>
            <div class="heart">❤</div>
          </div>

          <div class="info">
            <div class="name" :title="it.recipient">{{ it.recipient || '匿名' }}</div>
            <div class="amount">¥ {{ Number(it.totalAmount || 0).toLocaleString() }}</div>
            <div class="meta">
              <span>笔数：{{ it.count }}</span>
              <span class="dot"></span>
              <span>最近：{{ it.lastTime || '-' }}</span>
            </div>
          </div>

          <div class="actions">
            <el-button size="small" @click="goList(it.recipient)">查看明细</el-button>
            <el-button size="small" type="success" @click="quickDonate(it.recipient)">继续捐赠</el-button>
          </div>
        </div>
      </transition-group>
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import donationApi from '@/api/donation_api.js'; // 需要已有 page(...)；可选：summaryByRecipient()

const loading = ref(false);
const rawList = ref([]);   // 明细（用于顶部总额/笔数）
const cards = ref([]);     // 汇总卡片 [{recipient,totalAmount,count,lastTime,photo_url}]

const filter = ref({
  keyword: '',
  topN: 12,
  sortBy: 'amountDesc' // amountDesc | amountAsc | latest | name
});

// 顶部统计
const totalDonations = computed(() => rawList.value.length);
const grandTotal = computed(() => rawList.value.reduce((s, it) => s + Number(it.amount || 0), 0));
const totalRecipients = computed(() => cards.value.length);

// 可见卡片（搜索/排序/TopN）
const visibleCards = computed(() => {
  let list = [...cards.value];
  const kw = (filter.value.keyword || '').trim().toLowerCase();
  if (kw) list = list.filter(it => (it.recipient || '').toLowerCase().includes(kw));

  switch (filter.value.sortBy) {
    case 'amountAsc': list.sort((a,b)=>a.totalAmount-b.totalAmount); break;
    case 'latest': list.sort((a,b)=>new Date(b.lastTime||0)-new Date(a.lastTime||0)); break;
    case 'name': list.sort((a,b)=>(a.recipient||'').localeCompare(b.recipient||'')); break;
    default: list.sort((a,b)=>b.totalAmount-a.totalAmount); // amountDesc
  }
  const n = Number(filter.value.topN || 0);
  return n>0 ? list.slice(0,n) : list;
});

// 加载：优先后端汇总接口；否则分页聚合兜底
const load = async () => {
  loading.value = true;
  try {
    let summary = null;

    if (typeof donationApi.summaryByRecipient === 'function') {
      const s = await donationApi.summaryByRecipient().catch(() => null);
      summary = normalizeSummary(s);
    }
    if (!summary) {
      const res = await donationApi.page({ current: 1, limit: 5000 });
      const list = normalizePage(res);
      rawList.value = list;

      const map = new Map();
      list.forEach(it => {
        const name = it.recipient || '匿名';
        const curr = map.get(name) || { recipient: name, totalAmount: 0, count: 0, lastTime: '', photo_url: it.photo_url || '' };
        curr.totalAmount += Number(it.amount || 0);
        curr.count += 1;
        if (!curr.lastTime || new Date(it.donate_time || 0) > new Date(curr.lastTime || 0)) curr.lastTime = it.donate_time || curr.lastTime;
        if (!curr.photo_url && it.photo_url) curr.photo_url = it.photo_url;
        map.set(name, curr);
      });
      summary = Array.from(map.values());
    } else {
      // 汇总接口返回数据
      const res = await donationApi.page({ current: 1, limit: 1000 });
      rawList.value = normalizePage(res);
    }

    // 归一化数值类型
    cards.value = (summary || []).map(it => ({
      recipient: it.recipient || '匿名',
      totalAmount: Number(it.totalAmount || 0),
      count: Number(it.count || 0),
      lastTime: it.lastTime || '',
      photo_url: it.photo_url || ''
    }));
  } catch (e) {
    console.error(e);
    ElMessage.error('加载捐赠汇总失败');
  } finally {
    loading.value = false;
  }
};

// —— 各种后端返回结构的兼容处理 —— //
const normalizePage = (res) => {
  const root = res?.data ?? res ?? {};
  const box  = root.data ?? root;
  let list =
      (Array.isArray(box) ? box : null) ||
      box.data || box.list || box.records || box.rows || [];
  if (!Array.isArray(list) && Array.isArray(box?.data?.data)) list = box.data.data;
  // 字段映射
  return (list || []).map(it => ({
    donation_id : it.donation_id ?? it.donationId ?? it.id,
    order_id    : it.order_id    ?? it.orderId,
    recipient   : it.recipient,
    amount      : Number(it.amount || 0),
    donate_time : it.donate_time ?? it.donateTime,
    photo_url   : it.photo_url   ?? it.avatar ?? ''
  }));
};

const normalizeSummary = (res) => {
  const root = res?.data ?? res ?? {};
  const list = Array.isArray(root?.data) ? root.data : (Array.isArray(root) ? root : null);
  if (!Array.isArray(list)) return null;
  return list.map(it => ({
    recipient: it.recipient || '匿名',
    totalAmount: Number(it.totalAmount ?? it.amount ?? 0),
    count: Number(it.count ?? it.times ?? 0),
    lastTime: it.lastTime ?? it.latest ?? '',
    photo_url: it.photo_url ?? it.avatar ?? ''
  }));
};

// —— UI 工具 —— //
const initials = (name) => {
  if (!name) return '爱';
  const n = String(name).trim();
  const isAscii = /^[\x00-\x7F]+$/.test(n);
  return isAscii ? n.slice(0,2).toUpperCase() : n.slice(0,1);
};

const avatarStyle = (name) => {
  const seed = Array.from(String(name || 'love')).reduce((s, ch) => s + ch.charCodeAt(0), 0);
  const h = seed % 360, h2 = (h + 30) % 360;
  return {
    background: `linear-gradient(135deg, hsl(${h} 80% 85%), hsl(${h2} 85% 75%))`,
    color: `hsl(${h} 50% 35%)`
  };
};

// 跳到“捐赠记录”并带受助人筛选（按你路由实际修改）
const goList = (recipient) => {
  // this.$router.push({ path: '/donation/list', query: { recipient } })
  ElMessage.info(`可在“捐赠记录”页按受助人筛选：${recipient}`);
};

const quickDonate = (recipient) => {
  ElMessage.success(`已为「${recipient || '匿名'}」填好捐赠信息的默认表单～`);
};

onMounted(load);
</script>

<style scoped>
.donation-total { padding: 16px; }

/* 顶部横幅（与列表页一致风格） */
.hero {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr;
  gap: 16px;
  padding: 24px 20px;
  border-radius: 16px;
  background: linear-gradient(135deg, #fff3f1 0%, #fffbf7 100%);
  border: 1px solid #ffe0dc;
  box-shadow: 0 10px 30px rgba(255, 160, 160, 0.12);
  margin-bottom: 16px;
}
.hero-left h1 { margin: 0 0 8px; font-size: 22px; color: #d84315; font-weight: 700; }
.hero-left p { margin: 0 0 14px; color: #8d6e63; }
.hero-stats { display: flex; gap: 18px; flex-wrap: wrap; }
.stat { background: #fff; padding: 10px 14px; border-radius: 12px; border: 1px solid #ffe3de; }
.stat-num { font-size: 20px; font-weight: 700; color: #e53935; }
.stat-label { color: #8d6e63; font-size: 12px; }
.hero-right { display: flex; align-items: center; justify-content: center; }
.hero-illustration { width: 160px; height: 160px; }

/* 工具条 */
.toolbar-card { margin-bottom: 14px; }

/* 卡片墙 */
.grid { min-height: 200px; }
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 14px;
}
.card {
  background: #fff;
  border: 1px solid #ffe2d9;
  border-radius: 14px;
  padding: 14px;
  box-shadow: 0 6px 16px rgba(255, 160, 160, 0.08);
  display: grid;
  gap: 10px;
  transition: transform .2s ease, box-shadow .2s ease;
}
.card:hover { transform: translateY(-2px); box-shadow: 0 12px 24px rgba(255, 160, 160, 0.14); }

.photo { position: relative; width: 100%; aspect-ratio: 16/10; border-radius: 10px; overflow: hidden; background: #fff7f4; display: grid; place-items: center; }
.photo img { width: 100%; height: 100%; object-fit: cover; }
.avatar {
  width: 64px; height: 64px; border-radius: 50%;
  display: grid; place-items: center;
  font-weight: 800; font-size: 22px;
  box-shadow: inset 0 0 0 3px #fff;
}
.heart {
  position: absolute; right: 8px; top: 8px;
  background: rgba(255, 255, 255, .85);
  color: #e53935; font-weight: 700;
  padding: 2px 8px; border-radius: 999px; font-size: 12px;
  border: 1px solid #ffd4cf;
}

.info .name { font-weight: 700; color: #6d4c41; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.info .amount { font-size: 18px; font-weight: 800; color: #e53935; margin-top: 4px; }
.info .meta { color: #8d6e63; font-size: 12px; display: flex; align-items: center; gap: 8px; margin-top: 2px; }
.info .dot { width: 4px; height: 4px; background: #f1c8bf; border-radius: 50%; }

.actions { display: flex; gap: 8px; }

.fade-enter-active, .fade-leave-active { transition: all .2s ease; }
.fade-enter-from, .fade-leave-to { opacity: 0; transform: scale(.98); }

@media (max-width: 1024px) {
  .hero { grid-template-columns: 1fr; }
}
</style>
